package jjn.round1;

/**
 * @author Jjn
 * @since 2022/8/29 00:06
 */
public class LeetCode695_MaxAreaOfIsland {
    public int maxAreaOfIsland(int[][] grid) {
        int max = 0;
        int maxHeight = grid.length;
        int maxWidth = grid[0].length;
        for (int i = 0; i < maxHeight; i++) {
            for (int j = 0; j < maxWidth; j++) {
                if (grid[i][j] == 1) {
                    int dfs = dfs(grid, i, j);
                    max = Math.max(dfs, max);
                }
            }
        }
        return max;
    }

    private int dfs(int[][] grid, int i, int j) {
        int maxHeight = grid.length;
        int maxWidth = grid[0].length;
        if (i < 0 || i >= maxHeight || j < 0 || j >= maxWidth || grid[i][j] == 0) {
            return 0;
        }
        // 访问之后清除
        grid[i][j] = 0;
        int left = dfs(grid, i - 1, j);
        int right = dfs(grid, i + 1, j);
        int upper = dfs(grid, i, j - 1);
        int lower = dfs(grid, i, j + 1);
        return 1 + left + right + upper + lower;
    }
}
